﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using ProtoType.DataStorage;
using System.Xml.Linq;
using System.Windows.Navigation;
using System.IO.IsolatedStorage;
using System.IO;
using ProtoType.ProtoTypeService;

namespace ProtoType
{
    public partial class Layouts : PhoneApplicationPage
    {
        AppSettings apps = new AppSettings();
        ProtoTypeServiceClient client;
        DataStructureStore dss = new DataStructureStore();
        string selectedfid = "";

        public Layouts()
        {
            InitializeComponent();
            client = new ProtoTypeServiceClient();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (NavigationContext.QueryString.TryGetValue("fid", out selectedfid))
            {
                XDocument layoutDoc = XDocument.Load("SampleData/Layout.xml");
                var layouts = from layout in layoutDoc.Descendants("layout") select layout.Attribute("Name").Value;
                lstlayout.ItemsSource = layouts.ToList();
            }

        }

        private void lstlayout_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lstlayout.SelectedIndex != -1)
            {
                if (apps.IsolatedStorageSavingSetting)
                {
                    dss.SetformLayout(selectedfid, lstlayout.SelectedItem.ToString());
                    NavigationService.Navigate(new Uri("/LayOutControls.xaml?selectedfid=" + selectedfid, UriKind.Relative));
                }
                if (apps.WebServiceSavingSetting)
                {
                    client.SetformLayoutAsync(selectedfid, lstlayout.SelectedItem.ToString());
                    client.SetformLayoutCompleted += new EventHandler<SetformLayoutCompletedEventArgs>(client_SetformLayoutCompleted);
                }
            }
        }

        void client_SetformLayoutCompleted(object sender, SetformLayoutCompletedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/LayOutControls.xaml?selectedfid=" + selectedfid, UriKind.Relative));
        }
    }
}